package it.interazionemultimodale.twitterrecognizer.ui;

import it.interazionemultimodale.twitterrecognizer.R;
import it.interazionemultimodale.twitterrecognizer.twitterutility.TweetInfo;

import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class TweetAdapter extends BaseAdapter
{
	private LinkedList<TweetInfo> tweetList;
	
	private Context context;
	private int layoutResourceId;
	
	public TweetAdapter(Context context, int layoutResourceId)
	{
		this.tweetList = new LinkedList<TweetInfo>();
		this.context = context;
		this.layoutResourceId = layoutResourceId;
	}
	
	public void pushTweets(List<TweetInfo> list)
	{
		this.tweetList.addAll(0, list);
		this.notifyDataSetChanged();
	}
	
	public void addTweets(List<TweetInfo> list)
	{
		this.tweetList.addAll(list);
		this.notifyDataSetChanged();
	}
	
	@Override
	public int getCount()
	{
		return this.tweetList.size();
	}
	
	@Override
	public Object getItem(int position)
	{
		return tweetList.get(position);
	}
	
	public List<TweetInfo> getFirstNItems(int n)
	{
		LinkedList<TweetInfo> returnList = new LinkedList<TweetInfo>();
		int i = 0;
		for (TweetInfo tweetInfo : this.tweetList)
		{
			if (i++ >= n)
				break;
			returnList.add(tweetInfo);
		}
		return returnList;
	}
	
	@Override
	public long getItemId(int position)
	{
		return this.tweetList.get(position).getStatusId();
	}
	
	public long getFirstId()
	{
		TweetInfo lastTweetInfo = (TweetInfo) this.getItem(0);
		return (lastTweetInfo != null) ? lastTweetInfo.getStatusId() : 0;
	}
	
	public long getLastId()
	{
		TweetInfo lastTweetInfo = (TweetInfo) this.getItem(this.getCount() - 1);
		return (lastTweetInfo != null) ? lastTweetInfo.getStatusId() : 0;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		TweetInfo tweet = (TweetInfo)getItem(position);
		LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		
		if (convertView == null)
			convertView = layoutInflater.inflate(this.layoutResourceId, parent, false);
		
		((TextView) convertView.findViewById(R.id.desc)).setText(tweet.getStatusText());
		((TextView) convertView.findViewById(R.id.title)).setText(tweet.getUsername() + " - @" + tweet.getScreenName());
		((ImageView) convertView.findViewById(R.id.icon)).setImageBitmap(tweet.getBitmap());
		
		return convertView;
	}
}